package com.rainman.simpleredis.core.process_flow;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 辅助参数输入类
 *
 */
@Data
public class ProcessFlowBuilder {

   private String key;
   private Long dur;
    private List<String> work=new ArrayList<>();
    private List<String> paramInfo=new ArrayList<>();


    public static ProcessFlowBuilder newInstance(String key,Long dur) {

        ProcessFlowBuilder processFlowBuilder=new ProcessFlowBuilder(key, dur);
        return processFlowBuilder;
    }

    private ProcessFlowBuilder(String key, Long dur){
        this.key=key;
        this.dur=dur;

    }


    /**
     * 增加执行流
     * params支持以下写法，n要取之前的执行流
     *  #{n}第n个流的所有结果
     *  #{n.id}第n个流的结果的id字段
     *  其他的任意字符串
     *
     * @param workerName
     * @param params
     * @return
     */
    public ProcessFlowBuilder addWorker(String workerName,String... params){

        work.add(workerName);

        JSONArray jsonArray=new JSONArray();

        if(params==null||params.length<=0){

            jsonArray.add("");
        }else {
            for(String param:params){
                jsonArray.add(checkParam(param));
            }

        }
        paramInfo.add(jsonArray.toString());
        return this;
    }

    private String checkParam(String param){

        if(param==null){
            return "";
        }

        boolean dynParam = param.startsWith("#{");

        if(!dynParam){
            return param;
        }

        if(paramInfo.size()==0){
            throw new RuntimeException("首个参数不可为动态参数");
        }


        return param;
    }

}
